package com.upu173.music.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.andbase.library.asynctask.AbTask;
import com.andbase.library.asynctask.AbTaskItem;
import com.andbase.library.asynctask.AbTaskListener;
import com.andbase.library.asynctask.AbTaskObjectListener;
import com.andbase.library.utils.AbAppUtil;
import com.andbase.library.utils.AbDialogUtil;
import com.andbase.library.utils.AbToastUtil;
import com.upu173.music.R;
import com.upu173.music.fragment.FolderListFragment;
import com.upu173.music.fragment.MusicBarFragment;
import com.upu173.music.fragment.PlayListFragment;
import com.upu173.music.fragment.SongListFragment;
import com.upu173.music.model.PlayList;
import com.upu173.music.model.Song;
import com.upu173.music.model.SongFolder;
import com.upu173.music.receiver.PlayerManagerReceiver;
import com.upu173.music.service.MusicPlayerService;
import com.upu173.music.utils.MusicUtil;

import java.util.List;


public class MusicMainActivity extends MusicBaseActivity {

    private TextView toolSongMenu,toolFolderMenu;
    public PlayListFragment playListFragment;
    public FolderListFragment folderListFragment;
    private Fragment currentFragment;
    private boolean scaning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_activity_main);

        Toolbar toolbar = (Toolbar)this.findViewById(R.id.toolbar);
        initToolbar(toolbar,"",true);

        //检查权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            AbAppUtil.requestPermissions(this,new String []{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            },1024);

        }

        toolSongMenu = (TextView) findViewById(R.id.tool_menu_song);
        toolFolderMenu = (TextView) findViewById(R.id.tool_menu_folder);

        toolSongMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFragment(0);
            }
        });
        toolFolderMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFragment(1);
            }
        });

        playListFragment = new PlayListFragment();
        Bundle bundle = new Bundle();
        playListFragment.setArguments(bundle);

        folderListFragment = new  FolderListFragment();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.frame_layout, playListFragment).commit();
        currentFragment  = playListFragment;

        Intent startIntent = new Intent(this,MusicPlayerService.class);
        startService(startIntent);

    }

    public boolean showFragment(int index){
        if(index == 0){
            toolSongMenu.setTextColor(getResources().getColor(R.color.white));
            toolFolderMenu.setTextColor(getResources().getColor(R.color.toolbar_text_color));
            return switchFragment(playListFragment);
        }else if(index == 1){
            toolSongMenu.setTextColor(getResources().getColor(R.color.toolbar_text_color));
            toolFolderMenu.setTextColor(getResources().getColor(R.color.white));
            return switchFragment(folderListFragment);
        }
        return false;
    }

    private boolean switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        boolean isAdded = targetFragment.isAdded();
        if (!isAdded) {
            transaction.hide(currentFragment).add(R.id.frame_layout, targetFragment).commitAllowingStateLoss();
        } else {
            transaction.hide(currentFragment).show(targetFragment).commitAllowingStateLoss();
        }
        currentFragment  = targetFragment;
        return  isAdded;

    }

    public void addFolderClick(final int position){
        AbDialogUtil.showLoadingDialog(MusicMainActivity.this,-1,"添加到播放列表...");
        AbTask task = AbTask.newInstance();
        AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskObjectListener<List<Song>>() {
            @Override
            public List<Song> getObject() {
                SongFolder folder = folderListFragment.items.get(position);
                List<Song> songList = MusicUtil.getSongListFromFolder(MusicMainActivity.this,folder.getPath());
                MusicUtil.addPlayList(MusicMainActivity.this,songList);
                return songList;
            }

            @Override
            public void update(List<Song> songList) {
                AbDialogUtil.removeDialog(MusicMainActivity.this);

                AbDialogUtil.showAlertDialog(MusicMainActivity.this, "添加到播放列表：" + songList.size() + "首", "继续添加", "播放列表", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(MusicMainActivity.this);
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AbDialogUtil.removeDialog(MusicMainActivity.this);
                        showFragment(0);
                        playListFragment.loadData();
                    }
                });
            }
        });
        task.execute(item);

    }

    public void onPlayListDeleteClick(int position){
        PlayList song = playListFragment.items.get(position);
        MusicUtil.deletePlayList(this,song.get_id());
        playListFragment.removeItem(position);
        AbToastUtil.showToast(this,"从播放列表删除成功！");
    }


    public void onSongClick(int position){
        musicBarFragment.playSong(position);
    }

    public void onSongFolderClick(int position){
        SongFolder songFolder = folderListFragment.items.get(position);
        Intent intent = new Intent(this,MusicListActivity.class);
        intent.putExtra("folderName",songFolder.getName());
        intent.putExtra("folderPath",songFolder.getPath());
        startActivity(intent);
    }

    @Override
    public void back(View view) {

        /*Intent intent = new Intent(PlayerManagerReceiver.ACTION_MUSIC_PLAYER);
        intent.putExtra(PlayerManagerReceiver.MESSAGE_KEY,PlayerManagerReceiver.MESSAGE_RELEASE);
        sendBroadcast(intent);

        Intent stopIntent = new Intent(this,MusicPlayerService.class);
        stopService(stopIntent);*/

        super.back(view);
    }

    @Override
    public void finish() {
        super.finish();
    }

    private MenuItem scanMenuItem;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_scan, menu);
        scanMenuItem = menu.findItem(R.id.action_scan);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }else if(id == R.id.action_scan){
            AbToastUtil.showToast(this,"开始扫描本地歌曲...");
            scanSong();
        }else if(id == R.id.action_clear){
            MusicUtil.clearPlayList(this);
            playListFragment.loadData();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置是否刷新按钮变化
     */
    public void setRefreshActionButton(boolean refreshing) {
        if (refreshing) {
            MenuItemCompat.setActionView(scanMenuItem, R.layout.ab_toolbar_progress);
        } else {
            MenuItemCompat.setActionView(scanMenuItem, null);
        }
    }

    public void scanSong(){
        if(scaning){
            return;
        }
        setRefreshActionButton(true);
        scaning = true;
        AbTask task  = new AbTask();
        AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskListener(){
            @Override
            public void get() {
                MusicUtil.initSongList(MusicMainActivity.this);
            }

            @Override
            public void update() {
                setRefreshActionButton(false);
                folderListFragment.loadData();
                scaning = false;
            }
        });
        task.execute(item);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024 && AbAppUtil.hasAllPermissionsGranted(grantResults)) {
        } else {
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }
    }
}
